﻿using Newtonsoft.Json;
using Newtonsoft.Json.Converters;

namespace VaccineHost.Extend
{
    /// <summary>
    /// Json扩展
    /// </summary>
    public static class JsonExt
    {
        /// <summary>
        /// 对象转Json
        /// </summary>
        /// <param name="obj"></param>
        /// <returns></returns>
        public static string ToJson(this object obj)
        {
            if (obj != null && obj is string)
            {
                return obj.ToString();
            }

            var serializerSettings = new JsonSerializerSettings
            {
                // 设置为驼峰命名
                //ContractResolver = new CamelCasePropertyNamesContractResolver(),
                ReferenceLoopHandling = ReferenceLoopHandling.Ignore
            };

            serializerSettings.Converters.Add(new IsoDateTimeConverter { DateTimeFormat = "yyyy-MM-dd HH:mm:ss" });


            return JsonConvert.SerializeObject(obj, Formatting.Indented, serializerSettings);
        }

        /// <summary>
        /// Json转换为对象
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="json"></param>
        /// <returns></returns>
        public static T ToObject<T>(this string json)
            where T : class, new()
        {
            if (string.IsNullOrWhiteSpace(json))
            {
                return null;
            }
            return JsonConvert.DeserializeObject<T>(json, new JsonSerializerSettings
            {
                // 设置为驼峰命名
                //ContractResolver = new CamelCasePropertyNamesContractResolver(),
                ReferenceLoopHandling = ReferenceLoopHandling.Ignore
            });
        }

        /// <summary>
        /// 通过json转换对象
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="obj"></param>
        /// <returns></returns>
        public static T ConvertObject<T>(this object obj)
            where T : class, new()
        {
            string json = ToJson(obj);

            return ToObject<T>(json);
        }
    }
}
